package com.project.im.web.service;

import com.project.im.app.dto.WebUserLoginDTO;
import com.project.im.app.dto.WebUserRegisterDTO;
import com.project.im.common.enums.ResponseCode;
import com.project.im.common.enums.UserRole;
import com.project.im.common.exception.WebException;
import com.project.im.infra.entity.WebUser;
import com.project.im.infra.service.WebUserService;
import com.project.im.web.mapstruct.WebUserConverter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class AuthWebService {

    private final AuthenticationManager authenticationManager;
    private final PasswordEncoder passwordEncoder;
    private final WebUserService webUserService;
    private final WebUserConverter webUserConverter;
    private final TokenService tokenService;

    public String login(WebUserLoginDTO userLoginDTO) {
        UsernamePasswordAuthenticationToken authentication = UsernamePasswordAuthenticationToken.unauthenticated(userLoginDTO.getUsername(), userLoginDTO.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authentication);
        return tokenService.generateToken(authenticate.getPrincipal().toString());
    }

    public void register(WebUserRegisterDTO userRegisterDTO) {
        String username = userRegisterDTO.getUsername();
        if (webUserService.getByUsername(username) != null) {
            throw new WebException(ResponseCode.US101);
        }
        WebUser webUser = webUserConverter.convert(userRegisterDTO);
        String encode = passwordEncoder.encode(userRegisterDTO.getPassword());
        webUser.setPassword(encode);
        webUser.setRoles(UserRole.USER.name());
        webUserService.save(webUser);
    }
}
